package cn.jsj.hzu.qm.facecloud.user.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.hzu.jsj.utils.BeanFactory;
import cn.jsj.hzu.qm.facecloud.user.dao.UserDao;
import cn.jsj.hzu.qm.facecloud.user.pojo.User;
import cn.jsj.hzu.qm.facecloud.user.service.UserService;

/**
 * 与用户有关的servlet, 包括登录
 * 
 * @author 冯世新
 *
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/* 允许跨域 */
		/* 允许跨域的主机地址 */
		response.setHeader("Access-Control-Allow-Origin", "*");
		/* 允许跨域的请求方法GET, POST, HEAD 等 */
		response.setHeader("Access-Control-Allow-Methods", "*");
		/* 重新预检验跨域的缓存时间 (s) */
		response.setHeader("Access-Control-Max-Age", "3600");
		/* 允许跨域的请求头 */
		response.setHeader("Access-Control-Allow-Headers", "*");
		/* 是否携带cookie */
		response.setHeader("Access-Control-Allow-Credentials", "true");

		/* 不允许缓存 */
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("expires", -1);

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String base = request.getServletContext().getContextPath();

		int mode;
		String modeString = request.getParameter("mode");

		if (modeString == null) {
			response.getWriter().write("no mode");
			return;
		}

		mode = Integer.parseInt(modeString);
		UserService userService = BeanFactory.getBean("userService");
		// 1 增
		// 2 删
		// 3 改
		// 4 查
		//// 41 登录
		//// 42 登出
		//// 43 查询Session登录信息

		switch (mode) {

		// 41 登录
		case 41: {
			/**
			 * 实际上，email作为唯一登录名
			 */
			String usernameString = request.getParameter("username");
			String passwordString = request.getParameter("password");
			// 删除所有session
			request.getSession().invalidate();
			if (usernameString == null || passwordString == null) {
				return;
			}

			User user = userService.findUserByEmail(usernameString);

			if (user != null && passwordString.equals(user.getUser_password()) == true) {
				System.out.println("登陆成功：" + user);
				response.getWriter().write("login:success");
				request.getSession().setAttribute("login_user", user);
			} else {
				response.getWriter().write("login:error");
			}
			break;
		}

		// 42 登出
		case 42: {
			request.getSession().invalidate();
			response.sendRedirect(base + "/login.html");
			return;
		}

		// 43 查询Session登录信息
		case 43: {
			User user = (User) request.getSession().getAttribute("login_user");
			if (user == null) {
				System.out.println("未登录！");
				response.sendRedirect(base + "/errorPage/toLoginErrorPage.html");
				return;
			} else {
				response.getWriter().write(user.toJsonString());
				return;
			}
		}
		// 查询所有用户列表
		case 44: {
			User user = (User) request.getSession().getAttribute("login_user");
			if (user == null) {
				System.out.println("未登录！");
				response.sendRedirect(base + "/errorPage/toLoginErrorPage.html");
				return;
			} else {
				List<User> users = userService.findAllUsers();
				if (users == null) {
					response.getWriter().write("[]");
					return;
				} else {
					StringBuilder r = new StringBuilder();
					r.append("[");
					for (User my_user : users) {
						r.append(my_user.toJsonString());
						r.append(',');
					}
					r.append("]");

					response.getWriter().write(r.toString());
					return;
				}
			}
		}
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
